package process

import (
	"common-api/logs"
	"common-api/message"
	"common-api/serialization"
	"context"
	"sync"
)

var RequestHandlerMap sync.Map
var ResponseListerMap sync.Map

func RegisterRequestProcess(RequestCode int, handler Handler) {
	RequestHandlerMap.Store(RequestCode, handler)
}
func RegisterResponseListener(ResponseCode int, lens Listener) {
	ResponseListerMap.Store(ResponseCode, lens)
}

func ProcessRequestCommand(common *message.HeaderMessage, ctx context.Context) error {
	m, ok := RequestHandlerMap.Load(common.Code)
	if ok {
		var msg any
		switch common.Code {
		case message.LoginRequestCode:
			msg = &message.LoginReqData{}
			err := serialization.JsonDecode(common.Body, msg)
			if err != nil {
				logs.Logger.Debugf("message loginRequestData decode: %v", err)
				return err
			}
		case message.HeartRequestBeatCode:
			msg = &message.HeartBeatReqData{}
			err := serialization.JsonDecode(common.Body, msg)
			if err != nil {
				logs.Logger.Errorf("message heartBeatReqDatadecode: %v", err)
				return err
			}
		case message.RegisterRequestCode:
			msg = &message.RegisterReqData{}
			err := serialization.JsonDecode(common.Body, msg)
			if err != nil {
				logs.Logger.Errorf("message registerReqDatadecode: %v", err)
				return err
			}
		case message.PrivateChatRequestCode:
			msg = &message.PrivateChatReqData{}
			err := serialization.JsonDecode(common.Body, msg)
			if err != nil {
				logs.Logger.Errorf("message registerReqDatadecode: %v", err)
				return err
			}
		}
		m.(Handler).ProcessRequest(msg, ctx)
	}
	return nil
}

func ProcessResponseCommand(common *message.HeaderMessage) error {
	m, ok := ResponseListerMap.Load(common.Code)
	if ok {
		var msg any
		switch common.Code {
		case message.LoginResponseCode:
			msg = &message.LoginRespData{}
			err := serialization.JsonDecode(common.Body, msg)
			if err != nil {
				logs.Logger.Errorf("message loginRequestData decode: %v\n", err)
				return err
			}
		case message.CommonResponseCode:
			msg = &message.CommonRespData{}
			serialization.JsonDecode(common.Body, msg)
			err := serialization.JsonDecode(common.Body, msg)
			if err != nil {
				logs.Logger.Errorf("message loginRequestData decode: %v\n", err)
				return err
			}
		case message.PrivateChatResponseCode:
			msg = &message.PrivateChatRespData{}
			serialization.JsonDecode(common.Body, msg)
			err := serialization.JsonDecode(common.Body, msg)
			if err != nil {
				logs.Logger.Errorf("message loginRequestData decode: %v\n", err)
				return err
			}
		}
		m.(Listener).ProcessResponse(msg)
	}
	return nil
}

type Handler interface {
	ProcessRequest(data any, ctx context.Context)
}

type Listener interface {
	ProcessResponse(data any)
}
